<?php


namespace App\Services;



use App\Exceptions\ApiException;
use App\Models\AuthGroup;
use App\Models\AuthRule;

class AuthGroupService
{
    public function add(array $data)
    {
        $authgroup = AuthGroup::where('title', $data['title'])->first();
        if (!empty($authgroup)) {
            throw new ApiException(20006);
        }

        //判断rules是否合法
        $ruleIdArray = array_unique(explode(',', $data['rules']));
        $rulesCount = AuthRule::whereIn('id', $ruleIdArray)->count();
        if (count($ruleIdArray) !== $rulesCount) {
            throw new ApiException(50002);
        }

        $authgroup = new AuthGroup();
        $authgroup->title = $data['title'];
        $authgroup->status = $data['status'] ?? 0;
        $authgroup->rules = implode(',', $ruleIdArray);
        $authgroup->save();

    }

    public function edit(array $data)
    {
        $authgroup = AuthGroup::where('title', $data['title'])
            ->where('id', '<>', $data['id'])
            ->first();
        if (!empty($authgroup)) {
            throw new ApiException(20006);
        }

        //判断rules是否合法
        $ruleIdArray = array_unique(explode(',', $data['rules']));
        $rulesCount = AuthRule::whereIn('id', $ruleIdArray)->count();
        if (count($ruleIdArray) !== $rulesCount) {
            throw new ApiException(50002);
        }

        $authgroup = AuthGroup::find($data['id']);
        if (empty($authgroup)){
            throw new ApiException(30001);
        }
        $authgroup->title = $data['title'];
        $authgroup->status = $data['status'] ?? 0;
        $authgroup->rules = implode(',', $ruleIdArray);
        $authgroup->save();

    }

    public function del(int $id){
        $authgroup=AuthGroup::find($id);
        if (empty($authgroup)) {
            throw new ApiException(30001);
        }
        $authgroup->delete();
    }

    public function page($limit=15){
        $page = AuthGroup::select(['id','title','status','created_at'])->paginate($limit);
        return ['count'=>$page->total(),'data'=>$page->items()];
    }

}
